package com.zesionlee.server.service

import com.zesionlee.server.entity.FileEntity
import com.zesionlee.server.entity.UploadFileEntity
import com.zesionlee.server.exception.CustomException
import org.springframework.stereotype.Service
import java.io.File


@Service
class FileService {
    fun getSubList(sub: String): List<FileEntity> {
        return if (sub.isEmpty())
            File.listRoots().map { FileEntity(it.path, "disk", "") }
        else
            File(sub).listFiles()!!.map {
                if (it.isDirectory()) FileEntity(it.name, "dir", "") else FileEntity(it.name, "file", it.extension)
            }
    }

    fun uploadFile(uploadFileEntity: UploadFileEntity) {

        if (uploadFileEntity.files.isEmpty()) {
            throw CustomException("没有选择上次文件！")
        }

        if (File(uploadFileEntity.parent).exists() && File(uploadFileEntity.parent).isDirectory()) {

            for (file in uploadFileEntity.files) {
                file.transferTo(File(uploadFileEntity.parent + File.separator + file.name))
            }
        } else {
            throw CustomException("父级文件夹不存在")
        }
    }
}